package com.cqkqinfo.websocket.demo;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Slf4j
@Service
public class WebSocketHandler extends TextWebSocketHandler {


    private Map<String, WebSocketSession> sessionMap = new ConcurrentHashMap<>();

    @Override
    public void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        // 在这里处理从客户端发送过来的消息
        String reply =message.getPayload();
        log.info("服务端收到消息：{}", reply);
        session.sendMessage(new TextMessage(reply));
    }

    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        log.info("afterConnectionEstablished");
        sessionMap.put(session.getId(), session);
    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        log.info("afterConnectionClosed");
        sessionMap.remove(session.getId());
    }

    public void sendMessageToAll(String message) {
        sessionMap.values().forEach(session -> {
            try {
                session.sendMessage(new TextMessage(message));
            } catch (IOException e) {
                e.printStackTrace();
            }
        });
    }

/*    @Scheduled(fixedDelay = 10000)
    public void sendHeartBeat() {
        sendMessageToAll("HEARTBEAT");
    }*/
}